package com.blog.service.impl;

import com.blog.dto.GuestContent;
import com.blog.dto.Result;
import com.blog.entity.Guestbook;
import com.blog.entity.Users;
import com.blog.mapper.GuestbookMapper;
import com.blog.mapper.UsersMapper;
import com.blog.service.GuestbookService;
import com.blog.utils.JwtTokenProvider;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class GuestbookServiceImpl implements GuestbookService {
    @Resource
    private GuestbookMapper guestbookMapper;
    @Resource
    private JwtTokenProvider jwtTokenProvider;
    @Resource
    private UsersMapper usersMapper;
    @Override
    public void addguestbook(GuestContent guestContent) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username;
        String avatar;
        String guestbook = guestContent.getContent();
        if(authentication != null && authentication.isAuthenticated()
                && !(authentication instanceof AnonymousAuthenticationToken))  {
            username = jwtTokenProvider.getUsernameFromToken(authentication.getCredentials().toString());
            String email = jwtTokenProvider.getEmailFromToken(authentication.getCredentials().toString());
            Users user = usersMapper.findByEmail(email);
            avatar = user.getAvatar();
        }else {
            username = "游客";
            avatar = null;
        }
        Guestbook guestbooks = Guestbook.builder()
                        .content(guestbook)
                        .commentName(username)
                        .commentImage(avatar)
                        .build();
        guestbookMapper.addGuestbook(guestbooks);
    }

    @Override
    public List<Guestbook> getguestbook() {
        List<Guestbook> guestbooks = guestbookMapper.getguestbook();
        return guestbooks;
    }
}
